/**
 * 监控数据服务
 * 
 * 功能特性：
 * - 实时数据获取
 * - 历史数据查询
 * - 告警管理
 * - 性能指标计算
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import { 
  SystemMetrics, 
  AlertInfo, 
  DashboardConfig,
  TimeRange,
  MetricType,
  AlertSeverity
} from '../types/monitoring';

// API接口定义
interface MonitoringApi {
  getSystemMetrics: (timeRange: TimeRange) => Promise<SystemMetrics[]>;
  getRealTimeMetrics: () => Promise<SystemMetrics>;
  getAlerts: (status?: 'active' | 'resolved') => Promise<AlertInfo[]>;
  acknowledgeAlert: (alertId: string) => Promise<void>;
  getPerformanceStats: (timeRange: TimeRange) => Promise<PerformanceStats>;
  getHealthStatus: () => Promise<HealthStatus>;
  exportData: (timeRange: TimeRange, format: 'json' | 'csv') => Promise<Blob>;
}

// 性能统计接口
interface PerformanceStats {
  avgCpuUsage: number;
  maxCpuUsage: number;
  avgMemoryUsage: number;
  maxMemoryUsage: number;
  avgResponseTime: number;
  maxResponseTime: number;
  totalRequests: number;
  errorRate: number;
  availability: number;
  timestamp: string;
}

// 健康状态接口
interface HealthStatus {
  status: 'healthy' | 'warning' | 'critical';
  components: {
    database: 'healthy' | 'unhealthy';
    cache: 'healthy' | 'unhealthy';
    externalServices: 'healthy' | 'unhealthy';
    messageQueue: 'healthy' | 'unhealthy';
  };
  lastCheck: string;
}


class MonitoringService implements MonitoringApi {
  private baseUrl: string;
  private token: string;
  private wsConnection: WebSocket | null = null;
  private subscribers: Map<string, ((data: any) => void)[]> = new Map();

  constructor(baseUrl: string, token: string) {
    this.baseUrl = baseUrl;
    this.token = token;
    this.initializeWebSocket();
  }

  /**
   * 初始化WebSocket连接
   */
  private initializeWebSocket(): void {
    try {
      this.wsConnection = new WebSocket(
        `${this.baseUrl.replace('http', 'ws')}/ws/monitoring`
      );

      this.wsConnection.onopen = () => {
        console.log('WebSocket连接已建立');
        this.authenticate();
      };

      this.wsConnection.onmessage = (event) => {
        const data = JSON.parse(event.data);
        this.handleWebSocketMessage(data);
      };

      this.wsConnection.onclose = () => {
        console.log('WebSocket连接已关闭');
        this.reconnect();
      };

      this.wsConnection.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };
    } catch (error) {
      console.error('WebSocket初始化失败:', error);
    }
  }

  /**
   * WebSocket认证
   */
  private authenticate(): void {
    if (this.wsConnection && this.wsConnection.readyState === WebSocket.OPEN) {
      this.wsConnection.send(JSON.stringify({
        type: 'authenticate',
        token: this.token
      }));
    }
  }

  /**
   * 重新连接WebSocket
   */
  private reconnect(): void {
    setTimeout(() => {
      this.initializeWebSocket();
    }, 5000);
  }

  /**
   * 处理WebSocket消息
   */
  private handleWebSocketMessage(data: any): void {
    switch (data.type) {
      case 'metrics':
        this.notifySubscribers('metrics', data.payload);
        break;
      case 'alert':
        this.notifySubscribers('alerts', data.payload);
        break;
      case 'health':
        this.notifySubscribers('health', data.payload);
        break;
      default:
        console.warn('未知的消息类型:', data.type);
    }
  }

  /**
   * 通知订阅者
   */
  private notifySubscribers(eventType: string, data: any): void {
    const callbacks = this.subscribers.get(eventType) || [];
    callbacks.forEach(callback => callback(data));
  }

  /**
   * 订阅事件
   */
  public subscribe(eventType: 'metrics' | 'alerts' | 'health', callback: (data: any) => void): () => void {
    if (!this.subscribers.has(eventType)) {
      this.subscribers.set(eventType, []);
    }
    
    this.subscribers.get(eventType)!.push(callback);
    
    // 返回取消订阅函数
    return () => {
      const callbacks = this.subscribers.get(eventType) || [];
      const index = callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
    };
  }

  /**
   * 获取系统指标
   */
  public async getSystemMetrics(timeRange: TimeRange = '1h'): Promise<SystemMetrics[]> {
    try {
      const response = await fetch(`${this.baseUrl}/api/app/monitoring/performance-metrics`, {
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.data || [];
    } catch (error) {
      console.error('获取系统指标失败:', error);
      return this.generateMockMetrics(timeRange);
    }
  }

  /**
   * 获取实时指标
   */
  public async getRealTimeMetrics(): Promise<SystemMetrics> {
    try {
      const response = await fetch(`${this.baseUrl}/api/app/monitoring/performance-metrics/realtime`, {
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.data;
    } catch (error) {
      console.error('获取实时指标失败:', error);
      return this.generateSingleMockMetric();
    }
  }

  /**
   * 获取告警信息
   */
  public async getAlerts(status?: 'active' | 'resolved'): Promise<AlertInfo[]> {
    try {
      const url = status 
        ? `${this.baseUrl}/api/app/monitoring/alerts?status=${status}`
        : `${this.baseUrl}/api/app/monitoring/alerts`;
      
      const response = await fetch(url, {
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.data || [];
    } catch (error) {
      console.error('获取告警信息失败:', error);
      return this.generateMockAlerts();
    }
  }

  /**
   * 确认告警
   */
  public async acknowledgeAlert(alertId: string): Promise<void> {
    try {
      const response = await fetch(`${this.baseUrl}/api/app/monitoring/alerts/${alertId}/acknowledge`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    } catch (error) {
      console.error('确认告警失败:', error);
      throw error;
    }
  }

  /**
   * 获取性能统计
   */
  public async getPerformanceStats(timeRange: TimeRange = '1h'): Promise<PerformanceStats> {
    try {
      const response = await fetch(`${this.baseUrl}/api/app/monitoring/api-statistics?timeRange=${timeRange}`, {
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.data;
    } catch (error) {
      console.error('获取性能统计失败:', error);
      return this.generateMockPerformanceStats();
    }
  }

  /**
   * 获取健康状态
   */
  public async getHealthStatus(): Promise<HealthStatus> {
    try {
      const response = await fetch(`${this.baseUrl}/api/app/monitoring/health-check`, {
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.data;
    } catch (error) {
      console.error('获取健康状态失败:', error);
      return this.generateMockHealthStatus();
    }
  }

  /**
   * 导出数据
   */
  public async exportData(timeRange: TimeRange, format: 'json' | 'csv' = 'json'): Promise<Blob> {
    try {
      const response = await fetch(
        `${this.baseUrl}/api/app/monitoring/export?timeRange=${timeRange}&format=${format}`,
        {
          headers: {
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          }
        }
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.blob();
    } catch (error) {
      console.error('导出数据失败:', error);
      throw error;
    }
  }

  /**
   * 生成模拟数据
   */
  private generateMockMetrics(timeRange: TimeRange): SystemMetrics[] {
    const now = new Date();
    const data: SystemMetrics[] = [];
    let points = 0;
    
    switch (timeRange) {
      case '5m':
        points = 60;
        break;
      case '15m':
        points = 180;
        break;
      case '1h':
        points = 720;
        break;
      case '6h':
        points = 4320;
        break;
      case '24h':
        points = 17280;
        break;
      case '7d':
        points = 120960;
        break;
      case '30d':
        points = 518400;
        break;
    }

    for (let i = points; i >= 0; i--) {
      const timestamp = new Date(now.getTime() - i * (60000 / 12)); // 每5秒一个数据点
      data.push({
        timestamp: timestamp.toISOString(),
        cpuUsage: Math.random() * 100,
        memoryUsage: Math.random() * 100,
        diskUsage: Math.random() * 100,
        networkIn: Math.random() * 1000,
        networkOut: Math.random() * 1000,
        activeConnections: Math.floor(Math.random() * 1000) + 100,
        responseTime: Math.random() * 2000 + 100,
        throughput: Math.random() * 500 + 50
      });
    }

    return data;
  }

  /**
   * 生成单个模拟指标
   */
  private generateSingleMockMetric(): SystemMetrics {
    return {
      timestamp: new Date().toISOString(),
      cpuUsage: Math.random() * 100,
      memoryUsage: Math.random() * 100,
      diskUsage: Math.random() * 100,
      networkIn: Math.random() * 1000,
      networkOut: Math.random() * 1000,
      activeConnections: Math.floor(Math.random() * 1000) + 100,
      responseTime: Math.random() * 2000 + 100,
      throughput: Math.random() * 500 + 50
    };
  }

  /**
   * 生成模拟告警
   */
  private generateMockAlerts(): AlertInfo[] {
    const alerts: AlertInfo[] = [];
    const alertTypes = ['error', 'warning', 'info'] as const;
    const severities: AlertSeverity[] = ['low', 'medium', 'high', 'critical'];

    for (let i = 0; i < 10; i++) {
      alerts.push({
        id: `alert-${i}`,
        type: alertTypes[Math.floor(Math.random() * alertTypes.length)],
        title: `告警 ${i + 1}`,
        message: `这是第 ${i + 1} 个告警消息`,
        timestamp: new Date(Date.now() - Math.random() * 86400000).toISOString(),
        status: Math.random() > 0.5 ? 'active' : 'resolved',
        severity: severities[Math.floor(Math.random() * severities.length)]
      });
    }

    return alerts;
  }

  /**
   * 生成模拟性能统计
   */
  private generateMockPerformanceStats(): PerformanceStats {
    return {
      avgCpuUsage: Math.random() * 100,
      maxCpuUsage: Math.random() * 100,
      avgMemoryUsage: Math.random() * 100,
      maxMemoryUsage: Math.random() * 100,
      avgResponseTime: Math.random() * 2000 + 100,
      maxResponseTime: Math.random() * 5000 + 1000,
      totalRequests: Math.floor(Math.random() * 10000) + 1000,
      errorRate: Math.random() * 5,
      availability: 95 + Math.random() * 5,
      timestamp: new Date().toISOString()
    };
  }

  /**
   * 生成模拟健康状态
   */
  private generateMockHealthStatus(): HealthStatus {
    const components = ['database', 'cache', 'externalServices', 'messageQueue'];
    const healthStatus: HealthStatus = {
      status: 'healthy',
      components: {} as any,
      lastCheck: new Date().toISOString()
    };

    components.forEach(component => {
      healthStatus.components[component as keyof HealthStatus['components']] = 
        Math.random() > 0.1 ? 'healthy' : 'unhealthy';
    });

    // 如果有任何组件不健康，状态设为warning
    if (Object.values(healthStatus.components).some(status => status === 'unhealthy')) {
      healthStatus.status = 'warning';
    }

    return healthStatus;
  }

  /**
   * 关闭连接
   */
  public destroy(): void {
    if (this.wsConnection) {
      this.wsConnection.close();
      this.wsConnection = null;
    }
    this.subscribers.clear();
  }
}

export default MonitoringService;
export type { MonitoringApi, PerformanceStats, HealthStatus, TimeRange };